package com.doeis.jpush;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.doeis.common.utils.StringUtils;
import com.doeis.log.QueueManager;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.SystemProperties;
import com.doeis.push.BaiduServiceContext;
import com.doeis.push.PushBaidu;
import com.doeis.uwork.entity.mongo.MinaPushLog;
import com.voland.core.utils.DateUtils;
import com.voland.core.utils.IDGenerator;

/**
 * 类介绍     极光别名进行发送
 * @author tianbx
 * @version 2016年5月21日下午10:47:48
 */
public class DoeisJPushWithAlias {

	
	protected static final Logger LOG = LoggerFactory
			.getLogger(DoeisJPushWithAlias.class);
	
	public static void sendNotificationSet(Set<String> useridSet, String context) {
		MinaPushLog pushLog = new MinaPushLog();
		try{
			pushLog.setId(IDGenerator.uuid());
			pushLog.setStatus(false);
			pushLog.setUser_id(useridSet.toString());
			pushLog.setContent(context);
			pushLog.setCreateTime(DateUtils.currentDateTime());
			

			if (StringUtils.isBlank(context)) {
				context = "";
			}

			if (context.length() > 50) {
				context = context.substring(0, 50);
			}

			//android的用户
			Set<String> androidSet = new HashSet<String>();
			
			//静音
			Set<String> appstoreQuietSet1 = new HashSet<String>();
			Set<String> companyQuietSet1 = new HashSet<String>();
			//不静音
			Set<String> appstoreQuietSet = new HashSet<String>();
			Set<String> companyQuietSet = new HashSet<String>();
			
			Integer count  = null ;
			String  beQuiet = null;
			for(String userid : useridSet ){
				PushBaidu pushBaidu = BaiduServiceContext.getPlanBaidu(userid);
				if (pushBaidu == null) {
					continue ;
				}
				
				count = pushBaidu.getCount();
				if (count == null) {
					count = 0;
				}
				count += 1;
				pushBaidu.setCount(count);
				
				if(pushBaidu.getDevice_type()==null){
					androidSet.add(userid);
					continue ;
				}
				
				if( pushBaidu.getDevice_type() ==3  ){//android
					androidSet.add(userid);
				}else if( pushBaidu.getDevice_type() ==4 ){//ios
					beQuiet = pushBaidu.getQuiet();
					if(beQuiet==null){
						beQuiet = "1";
					}
					
					if(pushBaidu.getAppstore()!=null && pushBaidu.getAppstore()){//appstore证书
						if("1".equals(beQuiet)){
							appstoreQuietSet1.add(userid);
						}else{
							appstoreQuietSet.add(userid);
						}
					}else{//企业证书
						if("1".equals(beQuiet)){
							companyQuietSet1.add(userid);
						}else{
							companyQuietSet.add(userid);
						}	
					}
				}
			}
			
			//开始向极光推送-android
			if(androidSet.size()>0){
				String[] registrationID = new String[androidSet.size()];
				Map<String, String> extras = new HashMap<String, String>();
				extras.put("from", "JPush");
				sendNotificationAndroid(context, extras, androidSet.toArray(registrationID));
			}
			
			//ios-appstore-quite
			if(appstoreQuietSet1.size()>0){
				sendNotificationIosAppStore(context, "1", appstoreQuietSet1);
			}
			
			if(companyQuietSet1.size()>0){
				sendNotificationIosCompany(context, "1", companyQuietSet1);
			}
			
			if(appstoreQuietSet.size()>0){
				sendNotificationIosAppStore(context,  "0" , appstoreQuietSet);
			}
			
			if(companyQuietSet.size()>0){
				 sendNotificationIosCompany(context, "0", companyQuietSet);
			}
			
		}catch(Exception e){
			LOG.info("发送信息错误: {"+useridSet.toString()+ "}" + e.getMessage());
			e.printStackTrace();
			pushLog.setSendResult("发送信息错误: " + e.getMessage());
		}finally{
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(pushLog);
			}
		}
	}
	
	public static void main(String[] args) {
//		String[] userid = {"ff8080814871feda014877427b310084"};
//		Map<String, String> extras = new HashMap<String, String>();
//		extras.put("from", "JPush");
//		DoeisJPushWithAlias.sendNotificationAndroid("sdfsdf111",extras, userid);
		
		
		Set<String> setid = new HashSet<String>();
		setid.add("ff8080814e599e19014e6687ec9829c5");
		DoeisJPushWithAlias.sendNotificationIosCompany("111", "1", setid);
		
	}
	
	/**
	 * 方法介绍   向同一组android设备推送消息
	 * @param context
	 * @param useridset
	 * @author tianbx
	 * @version 2016年5月21日下午4:44:17
	 */
	public static void sendNotificationAndroid(String context, Map<String, String> extras, String ... alias ) {
		MinaPushLog pushLog = new MinaPushLog();
		try{
			pushLog.setId(IDGenerator.uuid());
			pushLog.setStatus(false);
			pushLog.setUser_id(alias.toString());
			pushLog.setContent(context);
			pushLog.setCreateTime(DateUtils.currentDateTime());
			
			JPushClient jpushClient =  new JPushClient(
					SystemProperties.getPushSecretKeyAndroid(),
					SystemProperties.getPushApiKeyAndroid(), 3);
			try {
				PushResult result = jpushClient.sendAndroidNotificationWithAlias("您有新消息", context, extras, alias);
				pushLog.setSendResult(result.getOriginalContent());
				pushLog.setStatus(true);
				LOG.info("Got JPush result - " + result.getOriginalContent());

			} catch (APIConnectionException e) {
				LOG.error("Connection error. Should retry later. ", e);
				pushLog.setSendResult("Connection error. Should retry later. "+e.getMessage());
			} catch (APIRequestException e) {
				LOG.error(
						"Error response from JPush server. Should review and fix it. ",
						e);
				LOG.info("HTTP Status: " + e.getStatus());
				LOG.info("Error Code: " + e.getErrorCode());
				LOG.info("Error Message: " + e.getErrorMessage());
				LOG.info("Msg ID: " + e.getMsgId());
				pushLog.setSendResult(e.getErrorMessage());
			}
		}catch(Exception e){
			LOG.info("发送信息错误: {"+alias.toString()+ "}" + e.getMessage());
			pushLog.setSendResult("发送信息错误: " + e.getMessage());
		}finally{
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(pushLog);
			}
		}
	}
	
	/**
	 * 方法介绍   ios企业证书
	 * @param context
	 * @param registrationID
	 * @author tianbx
	 * @version 2016年5月21日下午5:02:56
	 */
	public static void sendNotificationIosCompany(String context, String beQuiet, Set<String> alias ) {
		MinaPushLog pushLog = new MinaPushLog();
		try{
			pushLog.setId(IDGenerator.uuid());
			pushLog.setStatus(false);
			pushLog.setUser_id(alias.toString());
			pushLog.setContent(context);
			pushLog.setCreateTime(DateUtils.currentDateTime());
			
			JPushClient jpushClient =  new JPushClient(
					SystemProperties.getPushSecretKey(),
					SystemProperties.getPushApiKey(), 3);
			try {
				PushPayload payload =buildPushObject_ios_alias(context, beQuiet, alias);
				PushResult result = jpushClient.sendPush(payload);
				pushLog.setSendResult(result.getOriginalContent());
				pushLog.setStatus(true);
				LOG.info("Got JPush result - " + result.getOriginalContent());

			} catch (APIConnectionException e) {
				LOG.error("Connection error. Should retry later. ", e);
				pushLog.setSendResult("Connection error. Should retry later. "+e.getMessage());
			} catch (APIRequestException e) {
				LOG.error(
						"Error response from JPush server. Should review and fix it. ",
						e);
				LOG.info("HTTP Status: " + e.getStatus());
				LOG.info("Error Code: " + e.getErrorCode());
				LOG.info("Error Message: " + e.getErrorMessage());
				LOG.info("Msg ID: " + e.getMsgId());
				pushLog.setSendResult(e.getErrorMessage());
			}
		}catch(Exception e){
			LOG.info("发送信息错误: {"+alias.toString()+ "}" + e.getMessage());
			pushLog.setSendResult("发送信息错误: " + e.getMessage());
		}finally{
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(pushLog);
			}
		}
	}
	
	
	/**
	 * 方法介绍  ios- appstore证书
	 * @param context
	 * @param registrationID
	 * @author tianbx
	 * @version 2016年5月21日下午5:02:56
	 */
	public static void sendNotificationIosAppStore(String context, String beQuiet, Set<String> alias ) {
		MinaPushLog pushLog = new MinaPushLog();
		try{
			pushLog.setId(IDGenerator.uuid());
			pushLog.setStatus(false);
			pushLog.setUser_id(alias.toString());
			pushLog.setContent(context);
			pushLog.setCreateTime(DateUtils.currentDateTime());
			
			JPushClient jpushClient =  new JPushClient(
					SystemProperties.getPushSecretKeyAppstore(),
					SystemProperties.getPushApiKeyAppstore(), 3);
			try {
//				PushResult result = jpushClient.sendIosNotificationWithAlias(context, extras, alias);
				PushPayload payload =buildPushObject_ios_alias(context, beQuiet, alias);
				PushResult result = jpushClient.sendPush(payload);
				pushLog.setSendResult(result.getOriginalContent());
				pushLog.setStatus(true);
//				LOG.info("Got JPush result - " + result.getOriginalContent());

			} catch (APIConnectionException e) {
				LOG.error("Connection error. Should retry later. ", e);
				pushLog.setSendResult("Connection error. Should retry later. "+e.getMessage());
			} catch (APIRequestException e) {
				LOG.error(
						"Error response from JPush server. Should review and fix it. ",
						e);
				LOG.info("HTTP Status: " + e.getStatus());
				LOG.info("Error Code: " + e.getErrorCode());
				LOG.info("Error Message: " + e.getErrorMessage());
				LOG.info("Msg ID: " + e.getMsgId());
				pushLog.setSendResult(e.getErrorMessage());
			}
		}catch(Exception e){
			LOG.info("发送信息错误: {"+alias.toString()+ "}" + e.getMessage());
			pushLog.setSendResult("发送信息错误: " + e.getMessage());
		}finally{
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(pushLog);
			}
		}
	}
	
	/**
	 * 方法介绍   ios设备用户alias为标示, 单个用户
	 * @param userid
	 * @param context
	 * @param beQuiet
	 * @param count
	 * @return
	 * @author tianbx
	 * @version 2016年5月21日下午4:24:13
	 */
	public static PushPayload buildPushObject_ios_alias(String context, String beQuiet, Set<String> alias  ) {
		Options apnsProduction = null;
		if(2 == SystemProperties.getPushDeployStatus()){
			apnsProduction = Options.newBuilder()
			        .setApnsProduction(true)
			        .build();
		}else{
			apnsProduction = Options.newBuilder()
			        .setApnsProduction(false)
			        .build();
		}
		
		
		if ("1".equals(beQuiet)) {
			 return PushPayload.newBuilder()
		                .setPlatform(Platform.all())
		                .setAudience(Audience.alias(alias))
		                .setOptions(apnsProduction)
		                .setNotification(Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
//												.incrBadge(1)
												.setAlert(context)
//												.setBadge(count)
												.setSound("sound.caf")
												.addExtra("from", "JPush")
												.build()).build())
		                .build();
			
		} else {
			
			 return PushPayload.newBuilder()
		                .setPlatform(Platform.all())
		                .setOptions(apnsProduction)
		                .setAudience(Audience.alias(alias))
		                .setNotification(Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
												.setAlert(context)
//												.incrBadge(1)
//												.setBadge(count)
//												.setSound("")
												.disableSound()
//												.setSound(null)
												.addExtra("from", "JPush")
												.build()).build())
		                .build();
		}
	}
}
